import pandas as pd
import re
from bs4 import BeautifulSoup
import os


def extract_data_from_html(html_file):
    """从HTML文件中提取数据"""
    print(f"正在从 {html_file} 提取数据...")
    
    with open(html_file, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f.read(), 'html.parser')
    
    # 提取统计信息
    stats = {}
    stat_divs = soup.select(
        '.bg-blue-50, .bg-green-50, .bg-purple-50, '
        '.bg-yellow-50, .bg-orange-50'
    )
    for div in stat_divs:
        label = div.select_one('.text-sm').text.strip()
        value_text = div.select_one('.text-2xl').text.strip()
        
        # 处理百分比和货币格式
        if '%' in value_text:
            value = float(value_text.replace('%', '')) / 100
        elif '¥' in value_text:
            value = float(value_text.replace('¥', '').replace(',', ''))
        else:
            try:
                value = float(value_text)
            except ValueError:
                value = value_text
        
        stats[label] = value
    
    # 提取化妆师排班表
    makeup_schedule = []
    makeup_table = soup.select_one(
        'h2:-soup-contains("化妆师排班表")'
    ).find_next('table')
    if makeup_table:
        headers = [th.text.strip() for th in makeup_table.select('thead th')]
        
        for row in makeup_table.select('tbody tr'):
            cells = [td.text.strip() for td in row.select('td')]
            if cells:
                row_data = {'时间': cells[0]}
                for i, artist in enumerate(headers[1:], 1):
                    if i < len(cells):
                        # 提取房间号
                        if '直播间' in cells[i]:
                            match = re.search(r'直播间(\d+)', cells[i])
                            if match:
                                row_data[artist] = int(match.group(1))
                            else:
                                row_data[artist] = cells[i]
                        else:
                            row_data[artist] = cells[i]
                makeup_schedule.append(row_data)
    
    # 提取直播间使用情况
    room_schedule = []
    room_table = soup.select_one(
        'h2:-soup-contains("直播间使用情况")'
    ).find_next('table')
    if room_table:
        for row in room_table.select('tbody tr'):
            cells = [td.text.strip() for td in row.select('td')]
            if cells and len(cells) > 1:
                time = cells[0]
                for i, status in enumerate(cells[1:], 1):
                    if status and status != '-':
                        room_data = {
                            '时间': time,
                            '房间': i,
                            '状态': status
                        }
                        room_schedule.append(room_data)
    
    return {
        'stats': stats,
        'makeup_schedule': makeup_schedule,
        'room_schedule': room_schedule
    }


def export_to_csv(data, prefix):
    """将数据导出为CSV文件"""
    # 创建统计信息CSV
    stats_df = pd.DataFrame([data['stats']])
    stats_file = f"{prefix}_统计信息.csv"
    stats_df.to_csv(stats_file, index=False, encoding='utf-8-sig')
    print(f"统计信息已导出到 {stats_file}")
    
    # 创建化妆师排班表CSV
    if data['makeup_schedule']:
        makeup_df = pd.DataFrame(data['makeup_schedule'])
        makeup_file = f"{prefix}_化妆师排班表.csv"
        makeup_df.to_csv(makeup_file, index=False, encoding='utf-8-sig')
        print(f"化妆师排班表已导出到 {makeup_file}")
    
    # 创建直播间使用情况CSV
    if data['room_schedule']:
        room_df = pd.DataFrame(data['room_schedule'])
        room_file = f"{prefix}_直播间使用情况.csv"
        room_df.to_csv(room_file, index=False, encoding='utf-8-sig')
        print(f"直播间使用情况已导出到 {room_file}")


def process_all_html_files():
    """处理所有HTML文件"""
    html_files = [
        f for f in os.listdir() 
        if f.endswith('.html') and f.startswith('scheduling_report')
    ]
    
    for html_file in html_files:
        # 确定输出文件前缀
        is_q1_part1 = (
            html_file == 'scheduling_report_experiment1_part1.html' or 
            'q1_part1' in html_file
        )
        is_q1_part2 = (
            html_file == 'scheduling_report_experiment1_part2.html' or 
            'q1_part2' in html_file or 
            '100_makeup' in html_file
        )
        is_q2 = (
            html_file == 'scheduling_report_experiment2.html' or 
            'q2' in html_file
        )
        is_q3 = (
            html_file == 'scheduling_report_experiment3.html' or 
            'q3' in html_file
        )
        
        if is_q1_part1:
            prefix = '问题1_Part1'
        elif is_q1_part2:
            prefix = '问题1_Part2'
        elif is_q2:
            prefix = '问题2'
        elif is_q3:
            prefix = '问题3'
        else:
            prefix = html_file.replace('.html', '')
        
        # 提取并导出数据
        data = extract_data_from_html(html_file)
        export_to_csv(data, prefix)
        print(f"已完成 {html_file} 的数据导出\n")


if __name__ == "__main__":
    process_all_html_files()
    print("所有HTML文件已成功转换为CSV格式！")
